import 'dart:math' as math;
import 'package:components/lara_press_text.dart';
import 'package:common/export/tools.dart';
import 'package:flutter/material.dart';

/// 下拉刷新的状态
enum LaraPressRefreshStatus {
  idle,
  pulling,
  armed,
  refreshing,
  completed,
  failed,
}

/// 下拉刷新头部组件
class LaraPressRefreshHeader extends StatelessWidget {
  final LaraPressRefreshStatus status;
  final double progress;
  final double visibleExtent;

  const LaraPressRefreshHeader({
    super.key,
    required this.status,
    required this.progress,
    required this.visibleExtent,
  });

  @override
  Widget build(BuildContext context) {
    if (visibleExtent <= 0) {
      return const SizedBox.shrink();
    }
    // 使用 ConstrainedBox 限制最大高度，防止溢出
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 10.h),
      child: ConstrainedBox(
        constraints: BoxConstraints(
          maxHeight: visibleExtent,
          maxWidth: double.infinity,
        ),
        child: AnimatedContainer(
          duration: const Duration(milliseconds: 200),
          curve: Curves.easeOutCubic,
          child: _buildContent(context),
        ),
      ),
    );
  }

  Widget _buildContent(BuildContext context) {
    // 根据可见高度决定显示模式
    final isCompactMode = visibleExtent < 40;

    switch (status) {
      case LaraPressRefreshStatus.idle:
        return const SizedBox.shrink();

      case LaraPressRefreshStatus.pulling:
        return _buildPullingState(context, isCompactMode);

      case LaraPressRefreshStatus.armed:
        return _buildArmedState(context, isCompactMode);

      case LaraPressRefreshStatus.refreshing:
        return _buildRefreshingState(context, isCompactMode);

      case LaraPressRefreshStatus.completed:
        return _buildCompletedState(context, isCompactMode);

      case LaraPressRefreshStatus.failed:
        return _buildFailedState(context, isCompactMode);
    }
  }

  /// 自适应容器，根据模式显示不同内容
  Widget _buildAdaptiveContent({
    required Widget icon,
    required String text,
    required Color textColor,
    required bool isCompactMode,
    FontWeight? fontWeight,
  }) {
    if (isCompactMode) {
      // 紧凑模式：只显示图标
      return Center(
        child: FittedBox(fit: BoxFit.scaleDown, child: icon),
      );
    }

    // 完整模式：显示图标+文字，使用 Flexible 防止溢出
    return IntrinsicHeight(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Flexible(
            flex: 2,
            child: FittedBox(fit: BoxFit.scaleDown, child: icon),
          ),
          Flexible(
            flex: 1,
            child: Padding(
              padding: const EdgeInsets.only(top: 2),
              child: FittedBox(
                fit: BoxFit.scaleDown,
                child: LaraPressText(
                  text: text,
                  style: TextStyle(
                    fontSize: 12.sp,
                    color: textColor,
                    fontWeight: fontWeight,
                  ),
                  maxLines: 1,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 下拉状态
  Widget _buildPullingState(BuildContext context, bool isCompactMode) {
    return TweenAnimationBuilder<double>(
      duration: const Duration(milliseconds: 150),
      tween: Tween(begin: 0.0, end: progress),
      builder: (context, value, child) {
        final icon = Transform.rotate(
          angle: value * math.pi * 0.8,
          child: AnimatedScale(
            scale: 0.8 + value * 0.4,
            duration: const Duration(milliseconds: 100),
            child: Icon(
              Icons.keyboard_arrow_down_rounded,
              size: 28,
              color: Color.lerp(
                Colors.grey[400],
                Theme.of(context).primaryColor,
                value,
              ),
            ),
          ),
        );

        return _buildAdaptiveContent(
          icon: icon,
          text: '下拉刷新',
          textColor: Color.lerp(Colors.grey[400], Colors.grey[700], value)!,
          isCompactMode: isCompactMode,
        );
      },
    );
  }

  /// 准备状态
  Widget _buildArmedState(BuildContext context, bool isCompactMode) {
    return TweenAnimationBuilder<double>(
      duration: const Duration(milliseconds: 300),
      tween: Tween(begin: 0.0, end: 1.0),
      builder: (context, value, child) {
        final icon = AnimatedScale(
          scale: 1.0 + math.sin(value * math.pi * 4) * 0.1,
          duration: const Duration(milliseconds: 100),
          child: Container(
            padding: const EdgeInsets.all(4),
            decoration: BoxDecoration(
              color: Theme.of(context).primaryColor.withValues(alpha: 0.1),
              borderRadius: BorderRadius.circular(20),
            ),
            child: Icon(
              Icons.refresh_rounded,
              size: 28,
              color: Theme.of(context).primaryColor,
            ),
          ),
        );

        return _buildAdaptiveContent(
          icon: icon,
          text: '松开刷新',
          textColor: Theme.of(context).primaryColor,
          fontWeight: FontWeight.w600,
          isCompactMode: isCompactMode,
        );
      },
    );
  }

  /// 刷新状态
  Widget _buildRefreshingState(BuildContext context, bool isCompactMode) {
    final icon = SizedBox(
      width: 28,
      height: 28,
      child: CircularProgressIndicator(
        strokeWidth: 2,
        valueColor: AlwaysStoppedAnimation(Theme.of(context).primaryColor),
      ),
    );

    return _buildAdaptiveContent(
      icon: icon,
      text: '正在刷新...',
      textColor: Theme.of(context).primaryColor,
      isCompactMode: isCompactMode,
    );
  }

  /// 完成状态
  Widget _buildCompletedState(BuildContext context, bool isCompactMode) {
    return TweenAnimationBuilder<double>(
      duration: const Duration(milliseconds: 400),
      tween: Tween(begin: 0.0, end: 1.0),
      builder: (context, value, child) {
        final icon = AnimatedScale(
          scale: value,
          duration: const Duration(milliseconds: 400),
          curve: Curves.elasticOut,
          child: Container(
            padding: const EdgeInsets.all(4),
            decoration: BoxDecoration(
              color: Colors.green.withValues(alpha: 0.1),
              borderRadius: BorderRadius.circular(20),
            ),
            child: const Icon(
              Icons.check_circle_rounded,
              size: 28,
              color: Colors.green,
            ),
          ),
        );

        return _buildAdaptiveContent(
          icon: icon,
          text: '刷新完成',
          textColor: Colors.green,
          fontWeight: FontWeight.w500,
          isCompactMode: isCompactMode,
        );
      },
    );
  }

  /// 失败状态
  Widget _buildFailedState(BuildContext context, bool isCompactMode) {
    return TweenAnimationBuilder<double>(
      duration: const Duration(milliseconds: 400),
      tween: Tween(begin: 0.0, end: 1.0),
      builder: (context, value, child) {
        final icon = AnimatedScale(
          scale: value,
          duration: const Duration(milliseconds: 400),
          curve: Curves.elasticOut,
          child: Transform.translate(
            offset: Offset(math.sin(value * math.pi * 8) * 2, 0),
            child: Container(
              padding: const EdgeInsets.all(4),
              decoration: BoxDecoration(
                color: Colors.red.withValues(alpha: 0.1),
                borderRadius: BorderRadius.circular(20),
              ),
              child: const Icon(
                Icons.error_outline_rounded,
                size: 28,
                color: Colors.red,
              ),
            ),
          ),
        );

        return _buildAdaptiveContent(
          icon: icon,
          text: '刷新失败',
          textColor: Colors.red,
          fontWeight: FontWeight.w500,
          isCompactMode: isCompactMode,
        );
      },
    );
  }
}
